package com.liang.gulimall.ware.listener;

import com.liang.common.to.mq.OrderTo;
import com.liang.common.to.mq.StockLocked;
import com.liang.gulimall.ware.service.WareSkuService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Slf4j
@Service
@RabbitListener(queues = "stock.release.stock.queue")
public class StockRelesaeListener {
    @Autowired
    WareSkuService wareSkuService;
    @RabbitHandler
    public void handleStockLockedRelease(StockLocked stockLocked, Message message, Channel channel) throws IOException {
        log.info("收到解锁库存消息，开始解锁锁定的库存（自动解锁）");
        try {
            wareSkuService.unLock(stockLocked);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }

    }
    @RabbitHandler
    public void handleOrderCloseRelease(OrderTo order,Message message, Channel channel) throws IOException {
        try {
            wareSkuService.unLock(order);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }
}
